package cn.com.karl.reader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.library.Book;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.core.filesystem.ZLResourceFile;
import org.geometerplus.zlibrary.ui.android.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.artifex.mupdf.MuPDFActivity;

public class BookShelfActivity extends BaseActivity {
	BookShelfActivity context = this;
	private GridView bookShelf;
	private Button onlineStoreButton;
	private int[] data = { R.drawable.book1, R.drawable.pdf, R.drawable.bai, R.drawable.hao, R.drawable.huobi };
	private String[] name = { "", "", "", "", "" };

	private PopupWindow popupWindow;
	private boolean flag=true;

	private ListView lv_group;

	private View view;

	private View top_title;
	
	private TextView tv_head_local;

	private LinearLayout tvtitle;

	private List<String> groups;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.bookshelf);

		top_title = this.findViewById(R.id.head);
		tvtitle = (LinearLayout) top_title.findViewById(R.id.tv_head);
		
		tvtitle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				System.out.println("onClick");
				if(flag){
					flag=false;
					tvtitle.setBackgroundResource(R.drawable.bg_dropmenu_on);
					showWindow(v);
					Log.i("coder", "flag:" + flag);
				}else {
					flag=true;
					popupWindow.setFocusable(false);//失去焦点
					tvtitle.setBackgroundDrawable(new BitmapDrawable());
					popupWindow.dismiss();
					Log.i("coder", "flag:" + flag);
				}
			}
		});

		onlineStoreButton = (Button) findViewById(R.id.online_store);
		onlineStoreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, OnlineStoreActivity.class);
				startActivity(intent);
				context.finish();
			}
		});
		bookShelf = (GridView) findViewById(R.id.bookShelf);
		RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) bookShelf.getLayoutParams(); // 取控件mGrid当前的布局参数
		Log.i("bookShelf's linearParams.height = ", String.valueOf(linearParams.height));
		
		ShlefAdapter adapter = new ShlefAdapter();
		bookShelf.setAdapter(adapter);
		bookShelf.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg2 >= data.length) {

				} else {
					if (arg2 == 0) {
						ZLResourceFile file = ZLResourceFile.createResourceFile("data/book1.epub");
						openFile(file);
					} else if (arg2 == 1) {
						String path = Paths.cardDirectory() + "/Books/tianya2.pdf";
						File pdfFile = new File(path);
						if (!pdfFile.exists()) {
							ZLResourceFile file = ZLResourceFile.createResourceFile("data/tianya2.pdf");
							try {
								int bytesum = 0;
								int byteread = 0;
								InputStream inStream = file.getInputStream(); // 读入原文件
								FileOutputStream fs = new FileOutputStream(pdfFile);
								byte[] buffer = new byte[1444];
								int length;
								while ((byteread = inStream.read(buffer)) != -1) {
									bytesum += byteread; // 字节数 文件大小
									fs.write(buffer, 0, byteread);
								}
								inStream.close();
							} catch (Exception e) {
								System.out.println("复制单个文件操作出错");
								e.printStackTrace();

							}

						}
						Uri uri = Uri.parse(path);
						Intent intent = new Intent(context, MuPDFActivity.class);
						intent.setAction(Intent.ACTION_VIEW);
						intent.setData(uri);
						startActivity(intent);
						// context.finish();
					} else if (arg2 == 2) {
						ZLResourceFile file = ZLResourceFile.createResourceFile("data/bai.epub");
						openFile(file);
					} else if (arg3 == 3) {
						ZLResourceFile file = ZLResourceFile.createResourceFile("data/hao.epub");
						openFile(file);
					} else if (arg3 == 4) {
						ZLResourceFile file = ZLResourceFile.createResourceFile("data/huobi.epub");
						openFile(file);
					}
				}
			}
		});

	}

	private void openFile(ZLResourceFile file) {
		Book book = Book.getByFile(file);
		// startActivityForResult(new Intent(getApplicationContext(),
		// BookInfoActivity.class).putExtra(
		// BookInfoActivity.CURRENT_BOOK_PATH_KEY, book.File.getPath()), 1);
		// 直接打开书本
		startActivity(new Intent(getApplicationContext(), FBReader.class).setAction(Intent.ACTION_VIEW).putExtra(FBReader.BOOK_PATH_KEY, book.File.getPath())
				.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		context.finish();
	}

	class ShlefAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.length + 5;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View contentView, ViewGroup arg2) {
			// TODO Auto-generated method stub

			contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item1, null);

			ImageView view = (ImageView) contentView.findViewById(R.id.imageView1);
			Log.i("book height=", String.valueOf(view.getHeight()));
			if (data.length > position) {
				if (position < name.length) {
//					view.setText(name[position]);
				}
				view.setBackgroundResource(data[position]);
			} else {
				view.setBackgroundResource(data[0]);
				view.setClickable(false);
				view.setVisibility(View.INVISIBLE);
			}
			return contentView;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("你确定退出吗？").setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {

					// 先关闭Fbreader
					ZLApplication.Instance().closeWindow();
					finish();
				}
			}).setNegativeButton("返回", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	private void showWindow(View parent) {

		if (popupWindow == null) {
			LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			view = layoutInflater.inflate(R.layout.group_list, null);
//			ImageView iView = (ImageView)view.findViewById(R.id.iv_group_list_bg_divider1);
//			System.out.println("iv=" + iView.getWidth());
			lv_group = (ListView) view.findViewById(R.id.lvGroup);
			// 加载数据
			groups = new ArrayList<String>();
			groups.add("畅销排行");
			groups.add("言情小说");
			groups.add("励志管理");

			GroupAdapter groupAdapter = new GroupAdapter(this, groups);
			lv_group.setAdapter(groupAdapter);
			// 创建一个PopuWidow对象
			popupWindow = new PopupWindow(view, 300, 400);
			
//			popupWindow.getContentView().setOnTouchListener(new OnTouchListener(){
//
//	            @Override
//	            public boolean onTouch(View v, MotionEvent event) {
//	            	popupWindow.setFocusable(false);//失去焦点
//	            	tvtitle.setBackgroundDrawable(new BitmapDrawable());
//	            	popupWindow.dismiss();//消除pw
//	                return true;
//	            }
//			});
			popupWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					tvtitle.setFocusable(true);
					tvtitle.setBackgroundDrawable(null);
					flag = true;
				}
				
			});
		}

		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);

		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		WindowManager windowManager = (WindowManager) this.getWindowManager();
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
//		int xPos = windowManager.getDefaultDisplay().getWidth() / 2  - popupWindow.getWidth() / 2;
//		int xPos = windowManager.getDefaultDisplay().getWidth() / 2;
//		int xPos = parent.getWidth() / 2;
		DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int xPos = popupWindow.getWidth() / 2 - parent.getWidth() / 2;     // 屏幕宽度（像素）
        int height = metric.heightPixels;   // 屏幕高度（像素）
        
		Log.i("coder", "parent.getWidth():" + parent.getWidth());
		Log.i("coder", "window:" + windowManager.getDefaultDisplay().getWidth());
		Log.i("coder", "xPos:" + xPos);

		popupWindow.showAsDropDown(parent, -xPos, 0);

		lv_group.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

//				Toast.makeText(BookShelfActivity.this, groups.get(position), 1000).show();
				tv_head_local = (TextView)tvtitle.findViewById(R.id.tv_head_local);
				tv_head_local.setText(groups.get(position));
				if (popupWindow != null) {
					popupWindow.dismiss();
					tvtitle.setFocusable(true);
				}
			}
		});
	}
}